<?php
define('START_TIME', microtime(true));

date_default_timezone_set('America/Chicago');
define('IN_PRODUCTION', false);

define('APPLICATION_PATH', realpath('_system/application') . '/');
define('SYSTEM_PATH',      realpath('_system/system')      . '/');
define('MODULES_PATH',     realpath('_system/modules')     . '/');

// DO NOT CHANGE ANYTHING BELOW THIS LINE

require SYSTEM_PATH . 'library/array.php';
require SYSTEM_PATH . 'library/system.php';
require SYSTEM_PATH . 'library/request.php';

set_error_handler('errHndlr');
function errHndlr($level, $message, $file, $line)
{
	throw new ErrorException($message, 0, $level, $file, $line);
}

set_exception_handler('exceptionHndlr');
function exceptionHndlr($exception)
{
	try {
		ob_start();
		if (System::$inCli) {
			include System::locate('views/cli', 'exception.php');
		} else {
			header('HTTP/1.1 500 Internal Server Error', true, 500);
			include System::locate('views', 'exception.php');
		}
		echo ob_get_clean();
	} catch (Exception $e) {
		ob_end_clean();
		echo 'Uncaught '. $e;
	}
}
spl_autoload_register('autoloadHndlr');
function autoloadHndlr($class)
{
	$filename = str_replace('_', '/', strtolower($class));
	if ($path = System::locate('library', $filename . '.php')) {
		require $path;
		return true;
	}
	return false;
}

System::init(array(
	'modules' => array(
		'Directory' => MODULES_PATH . 'directory',
		'Shopping cart' => MODULES_PATH . 'cart',
		'User management' => MODULES_PATH . 'users',
		'Mail list' => MODULES_PATH . 'maillist',
		'CLI' => MODULES_PATH . 'cli',
)
));
Request::init();

try {
	$func = 'return str_replace(array(
			\'{execution_time}\',
			\'{memory_usage}\',
			\'{included_files}\',
			\'{database_queries}\',
		), array(
			number_format(microtime(true) - START_TIME, 4),
			number_format(memory_get_usage(true) / 1048576, 2),
			count(get_included_files()),
			Database::$queriesCount,
		), $output);';
	Request::execute(Request::$uri)->send(create_function('$output', $func));
} catch (Exception $e) {
	if (IN_PRODUCTION) {
		if ($e instanceof ForbiddenException) {
			$response = new Response(403, new View(System::$inCli ? 'cli/forbidden' : 'forbidden'));
		} elseif ($e instanceof NotFoundException) {
			$response = new Response(404, new View(System::$inCli ? 'cli/not-found' : 'not-found'));
		} else {
			throw $e;
		}
		$response->send();
	} else {
		throw $e;
	}
}